package com.github.wxiaoqi.security.crm.core.biz;

import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.github.wxiaoqi.security.crm.core.client.FlyrayBizService;
import com.github.wxiaoqi.security.crm.core.entity.Customer;
import com.github.wxiaoqi.security.crm.core.entity.MerchantAccount;
import com.github.wxiaoqi.security.crm.core.entity.MerchantAccountJournal;
import com.github.wxiaoqi.security.crm.core.entity.MerchantAccountJournalExt;
import com.github.wxiaoqi.security.crm.core.entity.MerchantBase;
import com.github.wxiaoqi.security.crm.core.entity.MerchantBaseExt;
import com.github.wxiaoqi.security.crm.core.entity.MerchantVerifyRecord;
import com.github.wxiaoqi.security.crm.core.mapper.MerchantAccountJournalExtMapper;
import com.github.wxiaoqi.security.crm.core.mapper.MerchantAccountJournalMapper;
import com.github.wxiaoqi.security.crm.core.mapper.MerchantBaseExtMapper;
import com.github.wxiaoqi.security.crm.core.mapper.MerchantBaseMapper;
import com.github.wxiaoqi.security.auth.common.util.CRC16M;
import com.github.wxiaoqi.security.auth.common.util.SnowFlake;
import com.github.wxiaoqi.security.common.biz.BaseBiz;
import com.github.wxiaoqi.security.common.crm.request.VerifiedRealNameParam;
import com.github.wxiaoqi.security.common.msg.AccountType;
import com.github.wxiaoqi.security.common.msg.ResponseCode;

import lombok.extern.slf4j.Slf4j;

/**
 * 商户基础信息
 *
 * @author centerroot
 * @email lfw6699@163.com
 * @date 2018-05-25 15:20:48
 */
@Slf4j
@Transactional(rollbackFor = Exception.class)
@Service
public class MerchantBaseBiz extends BaseBiz<MerchantBaseMapper,MerchantBase> {

	@Autowired
	private CustomerBiz customerBiz;
	@Autowired
	private MerchantBaseMapper merchantBaseMapper;
	@Autowired
	private MerchantBaseExtMapper merchantBaseExtMapper;
	@Autowired
	private MerchantAccountBiz merchantAccountBiz;
	@Autowired
	private MerchantAccountJournalMapper merchantAccountJournalMapper;
	@Autowired
	private MerchantAccountJournalExtMapper merchantAccountJournalExtMapper;
	
	@Autowired
	private FlyrayBizService flyrayBizService;
	@Value("${bountyHunter.acceptBizNo}")
	private String acceptBizNo;

	
	/**
	 * 获取悬赏中心统计数据
	 */
	public Map<String, Object> getMerStatistics(Map<String, Object> param){
		log.info("获取猎手中心统计数据 请求参数：{}",param);
		Map<String, Object> respMap = new HashMap<String, Object>();
		String merId = (String) param.get("merId");
		MerchantBase merchantBase = merchantBaseMapper.selectByPrimaryKey(merId);
		if (null != merchantBase) {
			// 查询用户可用悬赏币
			MerchantAccount reqMerAccBalance = new MerchantAccount();
			reqMerAccBalance.setMerId(merId);
			reqMerAccBalance.setAccType(AccountType.ACC_BALANCE.getCode());// 余额账户
			MerchantAccount respMerAccBalance = merchantAccountBiz.selectOne(reqMerAccBalance);
			if (null != respMerAccBalance && null != respMerAccBalance.getAccBalance()) {
				respMap.put("accBalance", respMerAccBalance.getAccBalance());
			}else{
				respMap.put("accBalance", "0.00");
			}
			// 查询用户冻结悬赏币
			MerchantAccount reqMerAccFreeze = new MerchantAccount();
			reqMerAccFreeze.setMerId(merId);
			reqMerAccFreeze.setAccType(AccountType.ACC_FREEZE.getCode());// 冻结账户
			MerchantAccount respMerAccFreeze = merchantAccountBiz.selectOne(reqMerAccFreeze);
			
			if (null != respMerAccFreeze && null != respMerAccFreeze.getAccBalance()) {
				respMap.put("freezeBalance", respMerAccFreeze.getAccBalance());
			}else{
				respMap.put("freezeBalance", "0.00");
			}
			
			MerchantBaseExt merchantBaseExt = merchantBaseExtMapper.selectByPrimaryKey(merId);
			
			if (null != merchantBaseExt && null != merchantBaseExt.getInterview()) {
				respMap.put("interview", merchantBaseExt.getInterview());
			}else{
				respMap.put("interview", "0");
			}
			// 收到待查看简历、进行中的任务
			Map<String, Object> reqRewardMap = new HashMap<String, Object>();
			reqRewardMap.put("merNo", merId);
			Map<String, Object> rewardMap = flyrayBizService.getRewardCenterInfo(reqRewardMap);
			if (null != rewardMap && ResponseCode.OK.getCode().equals(rewardMap.get("code"))) {
				respMap.put("noViewedCount", rewardMap.get("noViewedCount"));
				respMap.put("runningCount", rewardMap.get("runningCount"));
			}else{
				respMap.put("noViewedCount", "0");
				respMap.put("runningCount", "0");
			}
			
			respMap.put("code", ResponseCode.OK.getCode());
			respMap.put("msg", ResponseCode.OK.getMessage());
		}else{
			respMap.put("code", ResponseCode.MER_NOTEXIST.getCode());
			respMap.put("msg", ResponseCode.MER_NOTEXIST.getMessage());
		}
		
		return respMap;
	}
	/**
	 * 商户悬赏方实名认证
	 * 存入商户基本信息，修改注册用户商户编号字段
	 * */
	public Map<String, Object> verifiedMerchant(VerifiedRealNameParam param){
		Map<String, Object> respMap = new HashMap<String, Object>();
		String merId= String.valueOf(SnowFlake.getId());//商户信息id
		//String customerId =(String) param.get("customerId");//注册用户编号
		String customerIdStr = String.valueOf(SnowFlake.getId());
		String merchantNo = CRC16M.getCRCNo(customerIdStr);//商户号
		//String legalPersonName =(String) param.get("legalPersonName");//法人姓名
		//String legalPersonCredNo =(String) param.get("legalPersonCredNo");//法人身份证号
		//String custName=(String) param.get("custName");//公司名称
		//String businessLicence = (String) param.get("businessLicence");//营业执照照片
		MerchantBase merBase=new MerchantBase();
		merBase.setCustomerId(param.getCustomerId());
		try {
			MerchantBase newMerbase=merchantBaseMapper.selectOne(merBase);
			if(null!=newMerbase){//已认证
				respMap.put("code", ResponseCode.MERCHANT_ISEXIST.getCode());
				respMap.put("msg", ResponseCode.MERCHANT_ISEXIST.getMessage());
			}
			MerchantBase insertMerchant=new MerchantBase();
			insertMerchant.setMerId(merId);
			insertMerchant.setMerchantNo(merchantNo);
			insertMerchant.setCustomerId(param.getCustomerId());
			insertMerchant.setMerType("00");//普通商户
			insertMerchant.setCustName(param.getCustName());
			insertMerchant.setLegalPersonName(param.getLegalPersonName());
			insertMerchant.setLegalPersonCredNo(param.getLegalPersonCredNo());
			insertMerchant.setBusinessLicence(param.getBusinessLicence());
			insertMerchant.setAccountStatus("00");//账户状态 正常
			insertMerchant.setCreatetime(new Timestamp(System.currentTimeMillis()));
			insertMerchant.setUpdatetime(new Timestamp(System.currentTimeMillis()));
			int isInsertOk=merchantBaseMapper.insertSelective(insertMerchant);
			if(isInsertOk>0){
				respMap.put("code", ResponseCode.OK.getCode());
				respMap.put("msg", ResponseCode.OK.getMessage());
			}else{
				respMap.put("code", ResponseCode.MERCHANT_FAIL.getCode());
				respMap.put("msg", ResponseCode.MERCHANT_FAIL.getMessage());
			}
		} catch (Exception e) {
			e.printStackTrace();
			respMap.put("code", ResponseCode.MERCHANT_FAIL.getCode());
			respMap.put("msg", ResponseCode.MERCHANT_FAIL.getMessage());
		}
		return respMap;
	}
	
	/**
	 * 查询实名记录
	 * @param param
	 * @return
	 */
	public Map<String, Object> queryRealNameRecord() {
		log.info("查询企业实名认证记录参数。。。{}");
		Map<String, Object> respMap = new HashMap<String, Object>();
		List<MerchantVerifyRecord> res = merchantBaseMapper.queryRealNameRecord();
		log.info("查询企业实名认证记录。。。{}"+res);
		respMap.put("records", res);
		respMap.put("code", ResponseCode.OK.getCode());
		respMap.put("msg", ResponseCode.OK.getMessage());
		return respMap;
	}
	
	/**
	 * 修改实名状态
	 * @param param
	 * @return
	 */
	public Map<String, Object> updateVerifyFlag(Map<String, Object> param) {
		log.info("修改企业实名状态参数。。。{}"+param);
		Map<String, Object> respMap = new HashMap<String, Object>();
		merchantBaseMapper.updateVerifyFlag(param);
		log.info("修改企业实名状态完成。。。{}");
		respMap.put("code", ResponseCode.OK.getCode());
		respMap.put("msg", ResponseCode.OK.getMessage());
		return respMap;
	}
	
	/**
	 * 线下充值
	 * @author centerroot
	 * @time 创建时间:2018年6月22日上午11:36:33
	 * @param param
	 * @return
	 */
	public Map<String, Object> underlineRecharge(Map<String, Object> param) {
		log.info("线下充值    请求参数。。。{}",param);
		Map<String, Object> respMap = new HashMap<String, Object>();
		String rechargeType = (String) param.get("rechargeType");
		String invitationNumStr = (String) param.get("invitationNum");
		String rechargeAmt = (String) param.get("rechargeAmt");
		String merId = (String) param.get("merId");
		String platformId = (String) param.get("platformId");
		String operator = (String) param.get("operator");
		String operatorId = (String) param.get("operatorId");
		String orderNo = (String) param.get("orderNo");
		String orderType = (String) param.get("orderType");
		Integer invitationNum = 0;
		if (!StringUtils.isEmpty(invitationNumStr)) {
			invitationNum = Integer.valueOf(invitationNumStr);
		}
		
		if ("00".equals(rechargeType)) {
			// 00：余额充值
			Map<String, Object> depositMap = new HashMap<String, Object>();
			depositMap.put("merId", merId);
			depositMap.put("platformId", platformId);
			depositMap.put("accType", AccountType.ACC_BALANCE.getCode());
			depositMap.put("orderNo", orderNo);
			depositMap.put("orderType", orderType);
			depositMap.put("transferAmt", rechargeAmt);
			respMap = merchantAccountBiz.deposit(depositMap);
		}else if ("01".equals(rechargeType)) {
			// 01：邀请次数充值
			MerchantBaseExt merchantBaseExt = merchantBaseExtMapper.selectByPrimaryKey(merId);
			if (null == merchantBaseExt) {
				merchantBaseExt = new MerchantBaseExt();
				merchantBaseExt.setMerId(merId);
				merchantBaseExt.setInterview(invitationNum);
				merchantBaseExt.setCreatetime(new Timestamp(System.currentTimeMillis()));
				merchantBaseExtMapper.insert(merchantBaseExt);
			}else {
				merchantBaseExt.setInterview(merchantBaseExt.getInterview() + invitationNum);
				merchantBaseExt.setUpdatetime(new Timestamp(System.currentTimeMillis()));
				merchantBaseExtMapper.updateByPrimaryKey(merchantBaseExt);
			}
			
			MerchantAccountJournal merchantAccountJournal = new MerchantAccountJournal();
			String intoJournalId = String.valueOf(SnowFlake.getId());
			merchantAccountJournal.setJournalId(intoJournalId);
			merchantAccountJournal.setPlatformId(platformId);
			merchantAccountJournal.setOrderNo(orderNo);;
			merchantAccountJournal.setMerId(merId);
			merchantAccountJournal.setInOutFlag("1");//来账
			merchantAccountJournal.setTradeType(orderType);
			merchantAccountJournal.setCreatetime(new Timestamp(System.currentTimeMillis()));
			merchantAccountJournalMapper.insert(merchantAccountJournal);
			
			MerchantAccountJournalExt merchantAccountJournalExt = new MerchantAccountJournalExt();
			merchantAccountJournalExt.setJournalId(intoJournalId);
			merchantAccountJournalExt.setInvitationNum(invitationNum);
			merchantAccountJournalExt.setOperator(operator);
			merchantAccountJournalExt.setOperatorId(operatorId);
			merchantAccountJournalExt.setCreatetime(new Timestamp(System.currentTimeMillis()));
			merchantAccountJournalExtMapper.insert(merchantAccountJournalExt);
			
			respMap.put("code", ResponseCode.OK.getCode());
			respMap.put("msg", ResponseCode.OK.getMessage());
		}
		
		log.info("线下充值    响应参数。。。{}",respMap);
		return respMap;
	}
}